const express = require('express');
const { body, param } = require('express-validator');
const cartController = require('../controllers/cartController');
const { authenticate } = require('../middleware/auth');
const { validate } = require('../middleware/validation');

const router = express.Router();

// 所有购物车路由都需要认证
router.use(authenticate);

// 添加到购物车验证规则
const addToCartValidation = [
    body('productId')
        .isInt({ min: 1 })
        .withMessage('商品ID必须为正整数'),
    body('quantity')
        .optional()
        .isInt({ min: 1, max: 999 })
        .withMessage('数量必须在1-999之间')
];

// 更新购物车验证规则
const updateCartValidation = [
    param('id')
        .isInt({ min: 1 })
        .withMessage('购物车项ID必须为正整数'),
    body('quantity')
        .isInt({ min: 1, max: 999 })
        .withMessage('数量必须在1-999之间')
];

// 批量更新验证规则
const batchUpdateValidation = [
    body('items')
        .isArray({ min: 1 })
        .withMessage('必须提供商品列表'),
    body('items.*.id')
        .isInt({ min: 1 })
        .withMessage('商品ID必须为正整数'),
    body('items.*.quantity')
        .isInt({ min: 1, max: 999 })
        .withMessage('数量必须在1-999之间')
];

// 路由定义
router.get('/', cartController.getCart);
router.get('/count', cartController.getCartCount);
router.post('/', addToCartValidation, validate, cartController.addToCart);
router.put('/batch', batchUpdateValidation, validate, cartController.batchUpdateCart);
router.put('/:id', updateCartValidation, validate, cartController.updateCartItem);
router.delete('/:id', cartController.removeFromCart);
router.delete('/', cartController.clearCart);

module.exports = router;